package com.ciwong.epaper.modules.epaper.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.bean.AddEvent;
import com.ciwong.epaper.modules.epaper.adapter.BookCaseAdapter;
import com.ciwong.epaper.modules.epaper.bean.DeleteEP;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.bean.UserEpage;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.ui.BaseFragment;
import com.ciwong.epaper.ui.MainActivity;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.TitleBar;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 电子报  书桌
 *
 * @author RES-ZYLEI
 * @version ciwong v.1.0 2015-7-24
 * @since ciwong v.1.0
 */
public class EpaperFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener, View.OnClickListener {
    private final String TAG = "EpaperFragment";


    private static final int REQ_CODE_ADD_SERVICE = 100;// 添加服务

    public static final int REQ_CODE_TO_EDIT_BOOK = 101;// 去删除书籍

    public static final int REQ_CODE_TO_ADD_BOOK = 102;// 去添加书籍

    public static final int REQ_CODE_TO_BUY_SERVICE = 103;// 购买服务

    private static final int REQ_CODE_EXPIRE_TO_BUY_SERVICE = 104;// 已过期的服务去购买

    /**
     * 刷新书桌目录
     */
    public static final int REFRESH_LOCAL_BOOK_LIST = 1;
    /**
     * 刷新书桌目录
     */
    public static final int JUMP_TO_EDIT_BOOK = 2;


    public static final int ADD_DELETE_BOOK = 3;

    private View rootView;
    private BookCaseAdapter mBookCaseAdapter;
    protected boolean isRefesh = true;
    private RecyclerView recycler_view;
    private SwipeToLoadLayout swipeToLoadLayout;
    private View handle_no_book_tips;
    private View handle_no_net_tips;
    private TitleBar epaper_title_bar;
    private int mPageSize = 12;
    private int mPageIndex = 1;
    protected boolean isEmpty = false;
    private List<EpaperInfo> mEpaperInfoList = new ArrayList<>();
    private List<EpaperInfo> mDeleteInfoList = new ArrayList<>();
    private int width, height;
    private float bookWidth;
    private float bookHeight;

    private boolean isEditMode = false;
    private TextView btn_change_mode;
    private TextView btn_add_book;

    /**
     * 获取保存的书籍ID的KEY
     *
     * @return
     */
    private String getSaveBookIdKey() {
        return SerializableManager.SerializeKey.SHARE_KEY_BOOK_ID
                + SerializableManager.getInstance().getUserId(true);
    }

    /**
     * 创建一个实例
     *
     * @return 返回一个实例
     */
    public static EpaperFragment newInstance() {
        EpaperFragment epaperFragment = new EpaperFragment();
        return epaperFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_epaper, container, false);

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        findViews();
        initEvent();
        init();
        loadData();
        EventBus.getDefault().register(this);
    }

    /**
     * 初始化界面
     */
    private void findViews() {

        recycler_view = (RecyclerView) rootView.findViewById(R.id.swipe_target);
        swipeToLoadLayout = (SwipeToLoadLayout) rootView.findViewById(R.id.swipe_toLoad_layout);
        recycler_view.setLayoutManager(new LinearLayoutManager(getActivity()));
        epaper_title_bar = (TitleBar) rootView.findViewById(R.id.epaper_title_bar);
        handle_no_book_tips = rootView.findViewById(R.id.handle_no_book_tips);
        handle_no_net_tips = rootView.findViewById(R.id.handle_no_net_tips);

        btn_change_mode = (TextView) rootView.findViewById(R.id.btn_change_mode);
        btn_add_book = (TextView) rootView.findViewById(R.id.btn_add_book);
    }

    protected void initEvent() {
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);
        btn_change_mode.setOnClickListener(this);

        rootView.findViewById(R.id.btn_add_book).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEditMode) {
                    if (!mDeleteInfoList.isEmpty()) {
                        confirmDelet();
//                        toastInCenter("同学，你未选择任何删除书籍");
                    }

                } else {
                    EpaperJumpManager.jumpToAddBook(R.string.go_back, mActivity,
                            EpaperFragment.this, REQ_CODE_TO_ADD_BOOK);
                }
            }
        });

        rootView.findViewById(R.id.tx_add_book).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EpaperJumpManager.jumpToAddBook(R.string.go_back, mActivity,
                        EpaperFragment.this, REQ_CODE_TO_ADD_BOOK);
            }
        });

        rootView.findViewById(R.id.btn_retry).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isRefesh = true;
                mPageIndex = 1;
                getBookcaseFromNet(mPageIndex);

            }
        });


    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_change_mode) {

            if (!isEditMode) {
                changeEditMode(true);
//                isEditMode=true;
//                btn_change_mode.setText("取消");
//                btn_add_book.setText("删除");
//                btn_add_book.setTextColor( getResources().getColor(R.color.gray));
//                getActivity().sendBroadcast(new Intent(EpaperConstant.BROADCAST_HIDE_TAB_BAR));
            } else {
//                isEditMode=false;
//                btn_change_mode.setText("编辑");
//                btn_add_book.setText("添加");
//                btn_add_book.setTextColor( getResources().getColor(R.color.black));
//                getActivity().sendBroadcast(new Intent(EpaperConstant.BROADCAST_SHOW_TAB_BAR));
                changeEditMode(false);
            }

//            mBookCaseAdapter.setEditMode(isEditMode);
//            mBookCaseAdapter.notifyDataSetChanged();
        }

    }

    private void init() {
        width = getResources().getDisplayMetrics().widthPixels;
        height = getResources().getDisplayMetrics().heightPixels - DeviceUtils.dip2px(92);
//        float gHeight = height * 0.3f;
        float gWidth = width * 0.3f;
        bookWidth = gWidth;
        bookHeight = gWidth * 210 / 150;

        mBookCaseAdapter = new BookCaseAdapter(this, bookWidth, bookHeight);
        recycler_view.setAdapter(mBookCaseAdapter);
        epaper_title_bar.setTitle("书桌");
//        epaper_title_bar.setRightBtnText("全部");
        epaper_title_bar.hideBackBar();

    }


    public void loadData() {
//        refreshServiceAndBook(false);
        getLocalBookcase();
//        getBookcaseFromNet( mPageIndex);

    }

    /**
     * 获取缓存书籍列表key
     *
     * @return
     */
    private String getSerilizeBookListKey() {
        return SerializableManager.SerializeKey.SHARE_KEY_BOOKCASE;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (((MainActivity) mActivity)
                .getCurFragment() instanceof EpaperFragment) {
//            showHelpTip(false);
        }


    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(AddEvent event) {

        if (event.getEvent() == JUMP_TO_EDIT_BOOK) {
            EpaperJumpManager.jumpToEditBook(R.string.go_back, mActivity, EpaperFragment.this, mEpaperInfoList, EpaperFragment.REQ_CODE_TO_EDIT_BOOK);

        } else if (event.getEvent() == ADD_DELETE_BOOK) {

            if (event.isSelect()) {

                if (null == mDeleteInfoList) {
                    mDeleteInfoList = new ArrayList<>();
                }
                if (!mDeleteInfoList.contains(event.getEpaperInfo())) {
                    mDeleteInfoList.add(event.getEpaperInfo());
                }

            } else {
                if (mDeleteInfoList.contains(event.getEpaperInfo())) {
                    mDeleteInfoList.remove(event.getEpaperInfo());
                }
            }


            for (int i = 0; i < mBookCaseAdapter.getDataList().size(); i++) {
                if (mBookCaseAdapter.getDataList().get(i).getProductId().equals(event.getEpaperInfo().getProductId())) {
                    mBookCaseAdapter.getDataList().get(i).setSelectDelete(event.isSelect());
                    break;
                }
            }

            Log.d(TAG, "#######mDeleteInfoList.size()########" + mDeleteInfoList.size());

            if (mDeleteInfoList.isEmpty()) {
                btn_add_book.setTextColor(getResources().getColor(R.color.gray));
            } else {
                btn_add_book.setTextColor(getResources().getColor(R.color.red));
            }
        }

    }


    private void confirmDelet() {
        CWDialog confirmDialog = new CWDialog(getActivity());
        confirmDialog.setMessage(getString(R.string.str_confirm_delete, mDeleteInfoList.size()));
        confirmDialog.setPositiveButton(R.string.str_confirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface interDialog, int which) {
                        setDelBookcase();
                    }
                });
        confirmDialog.setNegativeButton(R.string.str_cancel, null);
        confirmDialog.setCanceledOnTouchOutside(true);
        confirmDialog.show();
    }

    /**
     * 获取本地书籍列表
     */
    public void getLocalBookcase() {
        SerializableManager.getInstance().deSerialize(getSerilizeBookListKey(),
                new BaseCallBack() {

                    @Override
                    public void failed(int errorCode, Object data) {

                        if (NetworkUtils.isOnline()) {
                            isRefesh = true;
                            mPageIndex = 1;
                            getBookcaseFromNet(mPageIndex);
                        } else {
                            handle_no_net_tips.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void failed(Object data) {
                    }

                    @Override
                    public void success(Object data) {

                        mEpaperInfoList = (List<EpaperInfo>) data;
                        mBookCaseAdapter.setDataList(mEpaperInfoList);
                        isRefesh = true;
                        mPageIndex = 1;
                        getBookcaseFromNet(mPageIndex);

                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQ_CODE_TO_BUY_SERVICE:
                case REQ_CODE_ADD_SERVICE:
//                    refreshServiceAndBook(true);
                    break;
                case REQ_CODE_EXPIRE_TO_BUY_SERVICE:// 已过期的服务购买成功
//                    refreshServiceAndBook(true);
                    break;
                case REQ_CODE_TO_ADD_BOOK:// 添加书籍完成
                    Log.d(TAG, "##### 添加书籍完成####");
                    isRefesh = true;
                    mPageIndex = 1;
                    getBookcaseFromNet(mPageIndex);
                    break;
                case REQ_CODE_TO_EDIT_BOOK:// 删除书籍完成
                    Log.d(TAG, "#####删除书籍完成####");
                    isRefesh = true;
                    mPageIndex = 1;
                    getBookcaseFromNet(mPageIndex);
                    break;
            }
        }
    }


    /**
     * 获取网络书籍列表
     */
    private void getBookcaseFromNet(int pageIndex) {

//        localBookList = bCaseAdapter.getEpaperInfos();

//        CWLog.e("TAT", "【EpaperFragment】 本地列表 localBookList=" + localBookList.size());
        if (SerializableManager.getInstance().getIsFirstLogin(true)) {
//            showCricleProgress();
        }

        if (null == EApplication.getInstance().getUserInfoBase()) {
            return;
        }

        EpaperDao.getInstance().getEpageBookcase(EApplication.BRAND_ID, pageIndex, mPageSize, new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                CWLog.e("TAT", "【EpaperFragment】    书籍列表获取失败1");
                showToastError(errorCode, data);
//                showEmptyUi(bCaseAdapter.getEpaperInfos() == null || bCaseAdapter.getEpaperInfos().size() == 0);
                swipeToLoadLayout.setRefreshing(false);
                swipeToLoadLayout.setLoadingMore(false);
                hideCricleProgress();
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                CWLog.e("TAT", "【EpaperFragment】    书籍列表获取失败2");
                hideCricleProgress();
                swipeToLoadLayout.setRefreshing(false);
                swipeToLoadLayout.setLoadingMore(false);

                if (!NetworkUtils.isOnline()) {
                    Log.d(TAG, "######无网络#####");
                    ToastUtil.INSTANCE.toastCenterNoNetError();
                    handle_no_net_tips.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void success(Object data) {
                CWLog.e("TAT", "【EpaperFragment】    书籍列表获取成功");

                swipeToLoadLayout.setRefreshing(false);
                swipeToLoadLayout.setLoadingMore(false);
                UserEpage userEpage = (UserEpage) data;
                List<EpaperInfo> netList = new ArrayList<EpaperInfo>();
                if (null != userEpage) {
                    netList = userEpage.getProduct();
                }

                if (isRefesh) {
                    if (null != netList && netList.size() > 0) {
                        isEmpty = false;
                        SerializableManager.getInstance().serialize(getSerilizeBookListKey(), (Serializable) netList);
                        mPageIndex++;
                    } else {
                        //数目为0
                        netList = new ArrayList<>();
                        isEmpty = true;
                    }
                    mEpaperInfoList = netList;

                    if (null != userEpage && userEpage.getTotalCount() == mEpaperInfoList.size()) {
                        EpaperInfo epaperInfo = new EpaperInfo();
                        epaperInfo.setAddEntrance(true);
                        mEpaperInfoList.add(epaperInfo);
                    }
                    mBookCaseAdapter.setDataList(mEpaperInfoList);

                } else {
                    if (null != netList && netList.size() > 0) {
                        isEmpty = false;
                        mEpaperInfoList.addAll(netList);
                        if (null != userEpage && userEpage.getTotalCount() == mEpaperInfoList.size()) {
                            EpaperInfo epaperInfo = new EpaperInfo();
                            epaperInfo.setAddEntrance(true);
                            mEpaperInfoList.add(epaperInfo);
                        }
                        mBookCaseAdapter.setDataList(mEpaperInfoList);
                        Log.d(TAG, "######mBookCaseAdapter.getDataList().size()#####" + mBookCaseAdapter.getDataList().size());
                        mPageIndex++;
                    } else {
                        Toast.makeText(getActivity(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                    }
                }

                handle_no_net_tips.setVisibility(View.GONE);
                if (isEmpty) {
                    handle_no_book_tips.setVisibility(View.VISIBLE);
                    btn_change_mode.setVisibility(View.INVISIBLE);
                    changeEditMode(false);
                    getActivity().sendBroadcast(new Intent(EpaperConstant.BROADCAST_SHOW_TAB_BAR));
                } else {
                    handle_no_book_tips.setVisibility(View.GONE);
                    btn_change_mode.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void changeEditMode(boolean isEdit) {
        if (!isEdit) {
            btn_change_mode.setText("编辑");
            isEditMode = false;
            mBookCaseAdapter.setEditMode(isEditMode);
            btn_add_book.setText("添加");
            btn_add_book.setTextColor(getResources().getColor(R.color.black));
            getActivity().sendBroadcast(new Intent(EpaperConstant.BROADCAST_SHOW_TAB_BAR));


            mBookCaseAdapter.setEditMode(isEditMode);

            mDeleteInfoList.clear();
            for (int i = 0; i < mBookCaseAdapter.getDataList().size(); i++) {
                mBookCaseAdapter.getDataList().get(i).setSelectDelete(false);
            }
            mBookCaseAdapter.notifyDataSetChanged();

        } else {

            isEditMode = true;
            btn_change_mode.setText("取消");
            btn_add_book.setText("删除");
            btn_add_book.setTextColor(getResources().getColor(R.color.gray));
            getActivity().sendBroadcast(new Intent(EpaperConstant.BROADCAST_HIDE_TAB_BAR));

            mBookCaseAdapter.setEditMode(isEditMode);
            mBookCaseAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onLoadMore() {
        isRefesh = false;
        getBookcaseFromNet(mPageIndex);
    }

    @Override
    public void onRefresh() {
        isRefesh = true;
        mPageIndex = 1;
        getBookcaseFromNet(mPageIndex);
    }


    /**
     * 删除书柜记录By书箱ID
     */
    public void setDelBookcase() {

        ArrayList<DeleteEP> deleteEPList = new ArrayList<>();

        for (EpaperInfo epaperInfo : mDeleteInfoList) {
            DeleteEP deleteEP = new DeleteEP();
            deleteEP.setProductId(epaperInfo.getProductId());
            deleteEP.setServiceId(epaperInfo.getServer().getId());
            deleteEPList.add(deleteEP);
        }


        if (deleteEPList.size() == 0) {
            return;
        }

        showCricleProgress();

        EpaperDao.getInstance().setDelBookcaseToServerByList(EApplication.BRAND_ID, deleteEPList, new BaseExtCallBack(getActivity()) {

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                CWLog.e("TAT", "setDelBookcase 上传失败");
                hideCricleProgress();
                Log.d(TAG, "######删除失败#####" + data.toString());
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                CWLog.e("TAT", "setDelBookcase 上传失败");
                hideCricleProgress();
            }

            @Override
            public void success(Object data) {
                CWLog.e("TAT", "setDelBookcase  上传成功");
                Log.d(TAG, "######删除成功#####");
                mDeleteInfoList.clear();
                changeEditMode(false);

                onRefresh();
                hideCricleProgress();
            }
        });
    }


}
